import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

typedef BoolCallback = void Function(bool markAdded);

// test http://img1.doubanio.com/view/photo/s_ratio_poster/public/p457760035.webp
///
/// 击图片变成订阅状态的缓存图片控件
///
class SubjectMarkImage extends StatefulWidget {
  final String imgNetUrl;
  final BoolCallback markAdd;
  final double? height;
  final double width;

  const SubjectMarkImage(this.imgNetUrl,
      {Key? key, required this.markAdd, this.width = 150.0, this.height})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SubjectMarkImageState(
        imgNetUrl, markAdd, width, width / 150.0 * 210.0);
  }
}

class _SubjectMarkImageState extends State<SubjectMarkImage> {
  bool markAdded = false;
  late String imgLocalPath, imgNetUrl;
  final BoolCallback markAdd;
  late Widget markAddedIcon, defaultMarkIcon;
  late Widget loadImg;
  final double imgWH = 28.0;
  late double height;
  late double width;

  _SubjectMarkImageState(this.imgNetUrl, this.markAdd, this.width, this.height);

  @override
  void initState() {
    super.initState();
    markAddedIcon = Image(
      image: const AssetImage('img/ic_subject_mark_added.png'),
      width: imgWH,
      height: imgWH,
    );
    defaultMarkIcon = ClipRRect(
      borderRadius: const BorderRadius.only(
          topLeft: Radius.circular(5.0), bottomRight: Radius.circular(5.0)),
      child: Image(
        image:
            const AssetImage('img/ic_subject_rating_mark_wish.png'),
        width: imgWH,
        height: imgWH,
      ),
    );
    var defaultImg =
        Image.asset('img/ic_default_img_subject_movie.9.png');

    loadImg = ClipRRect(
      child: CachedNetworkImage(
        imageUrl: imgNetUrl,
        width: width,
        height: height,
        fit: BoxFit.fill,
        placeholder: (BuildContext context, String url) {
          return defaultImg;
        },
        fadeInDuration: const Duration(milliseconds: 80),
        fadeOutDuration: const Duration(milliseconds: 80),
      ),
      borderRadius: const BorderRadius.all(Radius.circular(5.0)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: <Widget>[
        loadImg,
        GestureDetector(
          child: markAdded ? markAddedIcon : defaultMarkIcon,
          onTap: () {
            if (markAdd != null) {
              markAdd(markAdded);
            }
            setState(() {
              markAdded = !markAdded;
            });
          },
        ),
      ],
    );
  }
}
